<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="redis学习, Max|Blog">
    <meta name="description" content="life is a fucking movie">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>redis学习 | Max|Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.3.0"><link rel="alternate" href="/atom.xml" title="Max|Blog" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Max|Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Max|Blog</div>
        <div class="logo-desc">
            
            life is a fucking movie
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/zhy2021/zhy2021.github.io" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/zhy2021/zhy2021.github.io" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">redis学习</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/redis/">
                                <span class="chip bg-color">redis</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/redis/" class="post-category">
                                redis
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-07-04
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    12.6k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    53 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>写在前</strong>：学习笔记是结合尚学堂的课程和狂神的redis课程写的，狂神的视频地址：<a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1S54y1R7SB?p=1">https://www.bilibili.com/video/BV1S54y1R7SB?p=1</a></p>
<h1 id="redis学习"><a href="#redis学习" class="headerlink" title="redis学习"></a>redis学习</h1><h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p><img src="https://s1.ax1x.com/2020/07/04/NxbaA1.png" alt="经典"><br>在以前一个基本的网站访问量不会太大，单个数据库完全足够了</p>
<p><img src="https://s1.ax1x.com/2020/07/04/NxqcxU.png" alt="缓存"><br>我们希望去减轻数据的压力，可以用缓存来保证效率</p>
<h2 id="NoSQL"><a href="#NoSQL" class="headerlink" title="NoSQL"></a>NoSQL</h2><h3 id="NoSQL概述"><a href="#NoSQL概述" class="headerlink" title="NoSQL概述"></a>NoSQL概述</h3><blockquote>
<p>NoSQL = not only sql<br>非关系型数据库<br>随着互联网web2.0网站的兴起，传统的关系数据库在处理web2.0网站，特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心，出现了很多难以克服的问题，而非关系型的数据库则由于其本身的特点得到了非常迅速的发展。NoSQL数据库的产生就是为了解决大规模数据集合多重数据种类带来的挑战，尤其是大数据应用难题。Redis就是其中之一。</p>
</blockquote>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ul>
<li>方便拓展（数据之间没有关系，很好拓展）</li>
<li>大量数据高性能（Redis一秒写8w次，读取11w，性能高)</li>
<li>数据库类型是多样性的（不需要设计数据库，随取随用）</li>
<li>传统的RDBMS和NoSQL  <pre class="line-numbers language-none"><code class="language-none">传统的RDBMS
- 结构化组织
- SQL
- 数据和关系都存在单独的表中
- 操作数据定义语言
- 严格的一致性
- 基础的事务<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
  <pre class="line-numbers language-none"><code class="language-none">NoSQL
- 不仅仅是数据
- 没有固定的查询语言
- 键值对存储，列存储，文档存储，，，图像数据库，社交关系
- 最终一致性
- CAP定理和BASE（异地多活）
- 高性能，高可用，高可扩<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="分类"><a href="#分类" class="headerlink" title="分类"></a>分类</h3></li>
<li>KV键值对<ul>
<li>redis</li>
<li>tair</li>
<li>memecache</li>
</ul>
</li>
<li>文档型数据库（bson格式和json格式）<ul>
<li>mongoDB</li>
</ul>
</li>
<li>列存储数据库<ul>
<li>HBase</li>
<li>分布式文件系统</li>
</ul>
</li>
<li>图关系数据库<ul>
<li>Neo4j</li>
<li>InfoGrid</li>
</ul>
</li>
</ul>
<h2 id="Redis入门"><a href="#Redis入门" class="headerlink" title="Redis入门"></a>Redis入门</h2><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><blockquote>
<p>介绍  </p>
</blockquote>
<p>Redis（Remote Dictionary Server )，即远程字典服务，是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库，并提供多种语言的API。</p>
<blockquote>
<p>用途</p>
</blockquote>
<ul>
<li>内存存储，持久化（rdb，aof）</li>
<li>效率高，可以用于高速缓存</li>
<li>发布订阅系统</li>
<li>地图信息分析</li>
<li>计时器，计数器，浏览量</li>
<li>……</li>
</ul>
<blockquote>
<p>特性</p>
</blockquote>
<ul>
<li>多样的数据类型</li>
<li>持久化</li>
<li>集群</li>
<li>事务</li>
<li>……<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3>官网下载好.tar.gz压缩包，放入~目录中  </li>
</ul>
<blockquote>
<p>解压.tar.gz  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">tar</span> -zxvf redis<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://s1.ax1x.com/2020/07/05/US6fpR.png" alt="解压"></p>
<blockquote>
<p>需要安装gcc  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">yum <span class="token function">install</span> -y gcc-c++<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>编译 redis，进入解压完成的目录中  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#进入根目录执行</span>
<span class="token function">make</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p>安装 redis，在根目录中执行  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">make</span> <span class="token function">install</span> <span class="token assign-left variable">PREFIX</span><span class="token operator">=</span>/usr/local/redis
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>还在这个根目录中，把redis.conf复制到/usr/local/redis/bin中  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">cp</span> redis.conf /usr/local/redis/bin<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>修改redis.conf中的内容</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token builtin class-name">cd</span> /usr/local/redis/bin
<span class="token function">vim</span> redis.conf

<span class="token comment"># 1、修改</span>
<span class="token builtin class-name">bind</span> <span class="token number">127.0</span>.0.1 为bind <span class="token number">0.0</span>.0.0
<span class="token comment"># 2、修改daemonize</span>
daemonize no 改为 daemonize <span class="token function">yes</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>去usr/local/redis/bin中后台启动redis  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">./redis-server redis.conf<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h3 id="测试性能"><a href="#测试性能" class="headerlink" title="测试性能"></a>测试性能</h3><p><strong>redis-benchmark</strong>是官方自带的测试性能的工具，在bin目录中<br><img src="https://s1.ax1x.com/2020/07/04/NzEA3D.png" alt="参数配置"></p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"><span class="token comment">#测试100个并发连接，10w请求</span>
redis-benchmark -h localhost -p <span class="token number">6379</span> -c <span class="token number">100</span> -n <span class="token number">100000</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><img src="https://s1.ax1x.com/2020/07/04/NzAvjJ.png" alt="测试图"></p>
<h3 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a>基础知识</h3><p>redis默认有16个数据库（0-15），可以使用<code>select num</code>进行切换</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token keyword">select</span> <span class="token number">2</span> <span class="token comment">#切换数据库</span>
OK
<span class="token number">127.0</span>.0.1:6379<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token operator">></span> <span class="token keyword">select</span> <span class="token number">0</span>
OK<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>查看数据库大小：<code>dbsize</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> dbsize <span class="token comment"># 查看数据库大小</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>添加键值对：<code>set key value</code>和<code>get key</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> name zhy <span class="token comment"># 添加值</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> dbsize
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get name <span class="token comment"># 获取值</span>
<span class="token string">"zhy"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>查看当前数据库下的所有键：<code>keys *</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys * <span class="token comment">#查看当前数据库下的所有键</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"name"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"mylist"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"counter:__rand_int__"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"key:__rand_int__"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>清空数据库：<code>flushdb</code>和<code>flushall</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> flushdb <span class="token comment">#清空当前数据库</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> flushall <span class="token comment"># 清空所有数据库</span>
OK<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p><strong>Redis是单线程的</strong>  </p>
</blockquote>
<p>Redis是基于内存操作的，CPU不是Redis的瓶颈，而是机器内存和网络带宽。<br>Redis6.0以后好像有了多线程的功能</p>
<h3 id="Redis-Key"><a href="#Redis-Key" class="headerlink" title="Redis-Key"></a>Redis-Key</h3><blockquote>
<p>这些常用指令要熟记，在java中也是这些</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys * <span class="token comment">#查看当前数据库的所有key</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"name"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> exists name <span class="token comment">#判断当前key是否存在</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span> <span class="token comment">#存在时返回1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> exists qwe
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> move name <span class="token number">1</span> <span class="token comment">#移动当前key到其他数据库</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys *
<span class="token punctuation">(</span>empty list or <span class="token builtin class-name">set</span><span class="token punctuation">)</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> name zhy <span class="token comment">#设置一个key value</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> age <span class="token number">20</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get name <span class="token comment">#获取key的value</span>
<span class="token string">"zhy"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> expire name <span class="token number">10</span> <span class="token comment">#设置有效时长，单位second</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ttl name <span class="token comment">#查看key的剩余时长</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">5</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ttl name <span class="token comment"># key过期后时长为-2</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> -2
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get name
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span> <span class="token comment">#过期后获取不到了</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果有不会的命令可以去<a target="_blank" rel="noopener" href="http://www.redis.cn/commands.html">redis中文网</a>查看学习</p>
<h3 id="string类型"><a href="#string类型" class="headerlink" title="string类型"></a>string类型</h3><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> key1 v1 <span class="token comment"># 设置值</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get key1 <span class="token comment"># 获得值</span>
<span class="token string">"v1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys * <span class="token comment"># 获取所有的key</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"key1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> exists key1 <span class="token comment"># 判断是否存在</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> append key1 hello <span class="token comment"># 追加字符串</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">7</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get key1 
<span class="token string">"v1hello"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> append name zs <span class="token comment"># 如果当前key不存在，就会新建一个key</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> strlen key1 <span class="token comment"># 获取字符串长度</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">7</span>

<span class="token comment">###########################################################</span>

<span class="token comment">#自增和自减：incr/decr/incrby/decrby</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> views <span class="token number">0</span> <span class="token comment"># 初始浏览量为0</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get views
<span class="token string">"0"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> incr views <span class="token comment"># 自增1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> incr views
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get views
<span class="token string">"2"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> decr views <span class="token comment"># 自减1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> decr views
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get views
<span class="token string">"0"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> incrby views <span class="token number">10</span> <span class="token comment"># 设置增长值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">10</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> decrby views <span class="token number">5</span> <span class="token comment"># 设置自减值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">5</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get views
<span class="token string">"5"</span>

<span class="token comment">###########################################################</span>

<span class="token comment">#字符串范围：getrange key start end</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> key hello,redis <span class="token comment"># 设置key值</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get key
<span class="token string">"hello,redis"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getrange key <span class="token number">2</span> <span class="token number">6</span> <span class="token comment"># 截取字符串 [2,6]</span>
<span class="token string">"llo,r"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getrange key <span class="token number">0</span> -1 <span class="token comment"># 直接返回全部字符串，有的python的味道</span>
<span class="token string">"hello,redis"</span>

<span class="token comment">#替换：setrange key start string</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> key2 abcdefg <span class="token comment"># 设置值</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get ket2
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get key2
<span class="token string">"abcdefg"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setrange key2 <span class="token number">1</span> xxx 替换指定位置开始的字符串
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">7</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get key2
<span class="token string">"axxxefg"</span>

<span class="token comment"># del 删除</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get k2
<span class="token string">"v2"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> del k2 <span class="token comment"># 删除指定的key</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get k2
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span>

<span class="token comment">###########################################################</span>

<span class="token comment"># setex (set with expire)  设置过期时间</span>
<span class="token comment"># setnx (set if not exist)  不存在设置，，常常用于分布式锁中</span>


<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setex key3 <span class="token number">30</span> hello <span class="token comment"># 设置key3的值30秒后过期</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ttl key3 <span class="token comment"># 查看key3剩余时间</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">20</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setnx mykey redis <span class="token comment">#如果mykey不存在，创建并设置</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setnx mykey mysql <span class="token comment"># 因为mykey存在了，所以不成功</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get mykey
<span class="token string">"redis"</span>

<span class="token comment">###########################################################</span>

<span class="token comment">#mset</span>
<span class="token comment">#mget</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> mset k1 v1 k2 v2 k3 v3 <span class="token comment"># 同时设置多个值</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys *
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"k3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"k1"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"k2"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> mget k1 k2 k3 <span class="token comment"># 同时获取多个值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"v1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"v2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"v3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> msetnx k1 v1 k4 v4 <span class="token comment"># msetnx是原子性操作，一起成功或一起失败</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> keys *
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"k3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"k1"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"k2"</span>
<span class="token comment">###########################################################</span>

<span class="token comment"># 对象</span>
<span class="token builtin class-name">set</span> user:1 <span class="token punctuation">&#123;</span>name:zhangsan,age:3<span class="token punctuation">&#125;</span> <span class="token comment">#设置一个user:1对象值为json字符串保存</span>

<span class="token comment"># 这里的key是 user:&#123;id&#125;:&#123;field&#125;，在redis中完全ok</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> mset user:10001:name zhangsan user:10001:age <span class="token number">20</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> mget user:10001:name user:10001:age
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"zhangsan"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"20"</span>

<span class="token comment">###########################################################</span>

<span class="token comment">#getset  先get再set</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getset db mysql <span class="token comment">#如果不存在值，则返回nil，并设置</span>
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getset db redis <span class="token comment">#如果存在，获取并设置新的值</span>
<span class="token string">"mysql"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get db
<span class="token string">"redis"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>使用场景</p>
</blockquote>
<ul>
<li>计数器</li>
<li>统计多单位的数量</li>
</ul>
<h3 id="list类型"><a href="#list类型" class="headerlink" title="list类型"></a>list类型</h3><p>在redis中list可以被玩成栈，队列等等<br><img src="https://s1.ax1x.com/2020/07/04/NzwZY6.png" alt="双向链表"><br>所有list命令都是以<code>l</code>开头的</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">###########################################################</span>
<span class="token comment"># lpush 左插入</span>
<span class="token comment"># rpush 右插入</span>
<span class="token comment"># lrange 根据区间取值</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list <span class="token number">1</span> <span class="token comment">#将一个值或者多个值，插入列表头部（左）</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list <span class="token number">2</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list <span class="token number">3</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1 <span class="token comment">#获取所有值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> <span class="token number">1</span> <span class="token comment">#根据start和end获取值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>

<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> rpush list right 将一个值或者多个值插入到列表尾部（右）
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"right"</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># lpop  左移除第一个</span>
<span class="token comment"># rpop  右移除第一个</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"right"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpop list <span class="token comment"># 左移除第一个</span>
<span class="token string">"3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> rpop list <span class="token comment"># 右移除第一个</span>
<span class="token string">"right"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># lindex 通过下标获取值</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lindex list <span class="token number">1</span> <span class="token comment">#获取下标是1的值</span>
<span class="token string">"1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lindex list <span class="token number">0</span>
<span class="token string">"2"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># llen 获取列表的长度</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> llen list
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># lrem key num value  移除指定的值</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1 <span class="token comment">#获取所有的值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"bbb"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"bbb"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrem list <span class="token number">1</span> aaa <span class="token comment"># 移除一个aaa，并且是第一个</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"bbb"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"bbb"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrem list <span class="token number">2</span> bbb <span class="token comment"># 移除两个bbb</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"aaa"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># ltrim key start end 截取，裁断，并储存在key中</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello1
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello2
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello3
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ltrim list <span class="token number">1</span> <span class="token number">2</span> <span class="token comment">#通过下标截取指定的元素，list里只剩下了截取的元素</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"hello2"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"hello1"</span>

<span class="token comment">###########################################################</span>
<span class="token comment">#rpoplpush  移除列表尾部的一个元素，并移动到一个新的列表中</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello1
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list hello2
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get list2 <span class="token comment">#list2一开始不存在</span>
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> rpoplpush list list2 <span class="token comment"># 移除尾部第一个，放到list2的头部，不存在就创建</span>
<span class="token string">"hello"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"hello2"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"hello1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list2 <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"hello"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># lset 一切基于存在的前提下操作，把下角标对应的值替换掉</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lpush list a
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> LRANGE list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"a"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> LSET list <span class="token number">0</span> bbbb <span class="token comment"># 把下标是0的值替换掉</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> LRANGE list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"bbbb"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> LSET list <span class="token number">1</span> bbbb <span class="token comment"># 如果不存在就会报错</span>
<span class="token punctuation">(</span>error<span class="token punctuation">)</span> ERR index out of range

<span class="token comment">###########################################################</span>
<span class="token comment"># linsert key before/after value newValue  把某个值插入到某个元素的前面/后面</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> linsert list before <span class="token number">3</span> before <span class="token comment"># 在3的前面插入一个before</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">5</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> linsert list after <span class="token number">3</span> after <span class="token comment"># 在3的后面插入一个after</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">6</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> lrange list <span class="token number">0</span> -1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"before"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"after"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">6</span><span class="token punctuation">)</span> <span class="token string">"1"</span>

<span class="token comment">###########################################################</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>小结  </p>
</blockquote>
<ul>
<li>List实际上是一个链表，双向链表，before node after,left,right 都可以插入值</li>
<li>如果key不存在就创建新的链表</li>
<li>如果key存在，新增内容</li>
<li>如果移除所有值，链表就不存在了</li>
<li>在两边插入和改动值效率高，在中间插入效率低</li>
</ul>
<blockquote>
<p>用途</p>
</blockquote>
<ul>
<li>消息队列，消息排队</li>
</ul>
<h3 id="set类型"><a href="#set类型" class="headerlink" title="set类型"></a>set类型</h3><p>set中的值是唯一的，无序的</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">###########################################################</span>
<span class="token comment"># sadd key value 添加set值</span>
<span class="token comment"># smembers key  获取key中所有值</span>
<span class="token comment"># sismembers key value  判断value是不是key中的</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> sadd myset hello <span class="token comment">#添加值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> sadd myset redis
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> sadd myset world
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smembers myset <span class="token comment">#查看所有值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"hello"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"world"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"redis"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> sismember myset hello <span class="token comment"># 判断是不是成员</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> sismember myset he
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># scard key 获取key中的元素个数</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> scard myset <span class="token comment">#获取个数</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># srem key value  移除元素</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> srem myset hello
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># srandmember key [num=1] 随机取出指定个数的，默认1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smembers <span class="token builtin class-name">set</span> <span class="token comment">#查看所有</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span class="token number">6</span><span class="token punctuation">)</span> <span class="token string">"6"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> srandmember <span class="token builtin class-name">set</span> <span class="token comment">#随机取一个</span>
<span class="token string">"4"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> srandmember <span class="token builtin class-name">set</span>
<span class="token string">"1"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> srandmember <span class="token builtin class-name">set</span> <span class="token number">3</span> <span class="token comment"># 随机抽取指定个数的</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"6"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> srandmember <span class="token builtin class-name">set</span> <span class="token number">3</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># spop key  随机移除一个</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smembers <span class="token builtin class-name">set</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span class="token number">6</span><span class="token punctuation">)</span> <span class="token string">"6"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> spop <span class="token builtin class-name">set</span> <span class="token comment"># 随机移除一个</span>
<span class="token string">"5"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> spop <span class="token builtin class-name">set</span>
<span class="token string">"4"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smembers <span class="token builtin class-name">set</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"6"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># smove key1 key2 value将一个指定的值移动到另外一个key中</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smembers <span class="token builtin class-name">set</span> 
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> exists set3 <span class="token comment">#key3不存在</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> smove <span class="token builtin class-name">set</span> set3 <span class="token number">1</span> <span class="token comment">#将1从set移动到key3</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> exists set3 <span class="token comment"># 自动创建了key3</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SMEMBERS <span class="token builtin class-name">set</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SMEMBERS set3
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># 交集 intersection</span>
<span class="token comment"># 差集 Difference</span>
<span class="token comment"># 并集 Union</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SMEMBERS user1
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SMEMBERS user2
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SDIFF user1 user2 <span class="token comment">#差集 user1中有的user2中没有</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SDIFF user2 user1 <span class="token comment">#差集 user2中有的user1中没有</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SINTER user1 user2 <span class="token comment">#交集</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SUNION user1 user2 <span class="token comment">#并集</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"2"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"3"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"4"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"5"</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以用于做共同关注的功能，把好友，关注都封装到一个set中，存入redis</p>
<h3 id="hash类型"><a href="#hash类型" class="headerlink" title="hash类型"></a>hash类型</h3><p>Map集合，key-map，这时候的值是一个map，本质与string类型没太大区别<br><strong>大key 小key field</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">###########################################################</span>
<span class="token comment"># hset map key value 添加值</span>
<span class="token comment"># hget map key 获取值</span>
<span class="token comment"># hmset map key1 value1 key2 value2 ... 添加多个值</span>
<span class="token comment"># hmget map key1 key2 ...  获取多个值</span>
<span class="token comment"># hmgetall 获取所有信息，一键一值出现</span>
<span class="token comment"># hdel map key 删除指定的key</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hset myhash username zhangsan <span class="token comment">#添加值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hget myhash username <span class="token comment">#获取值</span>
<span class="token string">"zhangsan"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hmset myhash age <span class="token number">20</span> sex <span class="token number">0</span> <span class="token comment">#添加多个</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hmget myhash username age sex <span class="token comment">#获取多个</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"zhangsan"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"20"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"0"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hgetall myhash <span class="token comment">#获取所有信息，一键一值出现</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"username"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"zhangsan"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"age"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"20"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"sex"</span>
<span class="token number">6</span><span class="token punctuation">)</span> <span class="token string">"0"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hdel myhash sex <span class="token comment">#删除指定的key</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hgetall myhash
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"username"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"zhangsan"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"age"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"20"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># hlen map  获取表的key数量</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hlen myhash
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># hexists map key 判断key是否存在</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hexists myhash username
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># hvals map 只获得所有的value</span>
<span class="token comment"># hkeys map 只获得所有的key</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hkeys myhash <span class="token comment">#获取所有key</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"username"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"age"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hvals myhash <span class="token comment">#获取所有value</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"zhangsan"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"20"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># hincr 自增 hincrby 指定自增</span>
<span class="token comment"># hdecr 自减 hincrby 指定自减</span>
<span class="token comment"># hsetnx 如果不存在创建，存在就不创建</span>
<span class="token comment"># ...可以去string类型里查找</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hsetnx myhash num <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hsetnx myhash num <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hincrby myhash num <span class="token number">5</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">6</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> hincrby myhash num -25
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> -19
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>小结  </p>
</blockquote>
<p>hash适合存储经常变更的数据，比如用户对象，username,age什么的，<code>hset user:100001 username zhangsan age 20</code>，string更适合存储字符串</p>
<h3 id="zset类型"><a href="#zset类型" class="headerlink" title="zset类型"></a>zset类型</h3><p>在set的基础上增加了一个值，用于排序<br>格式是：<strong>key weight value</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">###########################################################</span>
<span class="token comment"># zadd key weight value key2 weight value2 添加</span>
<span class="token comment"># zRange key start end 遍历 从小到大</span>
<span class="token comment"># zRevRange key start end 从大到小</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zadd zset <span class="token number">1</span> one <span class="token comment"># 添加一个值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zadd zset <span class="token number">1</span> two
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zadd zset <span class="token number">99</span> thr
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zadd zset <span class="token number">10</span> four <span class="token number">6</span> five <span class="token comment"># 添加多个值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ZRANGE zset <span class="token number">0</span> -1 <span class="token comment"># 遍历所有，从小到大</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"one"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"two"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"five"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"four"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"thr"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zRevRange zset <span class="token number">0</span> -1 <span class="token comment"># 遍历从大到小</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"thr"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"four"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"five"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"two"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># zRangeByScore key min max [withScores]</span>
<span class="token comment"># -inf 无穷小 +inf 无穷大</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ZRANGEBYSCORE zset -inf +inf
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"one"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"two"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"five"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"four"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"thr"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> ZRANGEBYSCORE zset -inf +inf withscores <span class="token comment">#附带权值</span>
 <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"one"</span>
 <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
 <span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"two"</span>
 <span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"1"</span>
 <span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"five"</span>
 <span class="token number">6</span><span class="token punctuation">)</span> <span class="token string">"6"</span>
 <span class="token number">7</span><span class="token punctuation">)</span> <span class="token string">"four"</span>
 <span class="token number">8</span><span class="token punctuation">)</span> <span class="token string">"10"</span>
 <span class="token number">9</span><span class="token punctuation">)</span> <span class="token string">"thr"</span>
<span class="token number">10</span><span class="token punctuation">)</span> <span class="token string">"99"</span>

<span class="token comment">###########################################################</span>
<span class="token comment"># zrem 移除key中的元素</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zrem zset one <span class="token comment"># 移除</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># zcard 显示key有多少值</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zcard zset
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span class="token comment">###########################################################</span>
<span class="token comment"># zcount key start end 显示区间中的个数</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zcount zset <span class="token number">1</span> <span class="token number">50</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>

<span class="token comment">###########################################################</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>总结</p>
</blockquote>
<ul>
<li>存储班级成绩表，工资表</li>
<li>排行榜</li>
<li>普通消息，重要消息，带权重进行判断</li>
</ul>
<h3 id="geospatial-地理位置-类型"><a href="#geospatial-地理位置-类型" class="headerlink" title="geospatial(地理位置)类型"></a>geospatial(地理位置)类型</h3><blockquote>
<p>朋友圈定位，附近的人，打车距离计算</p>
</blockquote>
<h4 id="相关命令"><a href="#相关命令" class="headerlink" title="相关命令"></a>相关命令</h4><ul>
<li>geoAdd</li>
<li>geoDist</li>
<li>geoHash</li>
<li>geoPos</li>
<li>geoRadius</li>
<li>geoRadiusByMember<blockquote>
<p>geoAdd  </p>
</blockquote>
</li>
</ul>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># geoadd key  经度 维度 名称</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> geoadd china:city <span class="token number">112.83</span> <span class="token number">36.83</span> wuxiang
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> geoadd china:city <span class="token number">116.46</span> <span class="token number">39.92</span> beijing <span class="token number">117.2</span> <span class="token number">39.13</span> tianjin
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">2</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>geoPos  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># getpos key name1 name2 name 3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> geopos china:city beijing changzhi taiyuan <span class="token comment">#获取值</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"116.45999997854232788"</span>
   <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"39.9199990416181052"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"113.0799981951713562"</span>
   <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"36.18000022796537252"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"112.53000050783157349"</span>
   <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"37.87000021374301895"</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>geodist 返回两个位置间的距离</p>
</blockquote>
<p>单位：</p>
<ul>
<li>m</li>
<li>km</li>
<li>mi 英里</li>
<li>ft 英尺<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> geodist china:city beijing taiyuan <span class="token comment"># 北京到太原的距离</span>
<span class="token string">"409485.2048"</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p>georadius 以给定的经度纬度为中心，，找出某一半径内的元素  </p>
</blockquote>
</li>
</ul>
<p>附近的人（获得所有附近的人的定位通过半径查询）</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># georadius key 你的经度 你的维度 半径 单位 [withdist withcoord count 限定显示的数]</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> georadius china:city <span class="token number">112</span> <span class="token number">37</span> <span class="token number">10</span> km <span class="token comment"># 寻找半径10km</span>
<span class="token punctuation">(</span>empty array<span class="token punctuation">)</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> georadius china:city <span class="token number">112</span> <span class="token number">37</span> <span class="token number">120</span> km
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"wuxiang"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"taiyuan"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> georadius china:city <span class="token number">112</span> <span class="token number">37</span> <span class="token number">200</span> km
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"changzhi"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"wuxiang"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"taiyuan"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> georadius china:city <span class="token number">112</span> <span class="token number">37</span> <span class="token number">200</span> km withdist withcoord count <span class="token number">1</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"wuxiang"</span>
   <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"76.1938"</span>
   <span class="token number">3</span><span class="token punctuation">)</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"112.83000022172927856"</span>
      <span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"36.82999905262392559"</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>geohash 返回一个或多个位置的geohash表示</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># geohash key name1 name2 name3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> geohash china:city changzhi taiyuan beijing <span class="token comment">#将二维的经纬度转换成字符串，字符串越长越精准，两个字符串越接近地理位置也就越接近</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"ww2mv4q7fb0"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"ww8p2wjbep0"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"wx4g455wfe0"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="geo底层原理"><a href="#geo底层原理" class="headerlink" title="geo底层原理"></a>geo底层原理</h4><blockquote>
<p>geo底层的实现原理就算Zset！我们可以用Zset的命令来操作geo  </p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zrange china:city <span class="token number">0</span> -1 <span class="token comment"># 查看范围中的元素</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"changzhi"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"wuxiang"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"taiyuan"</span>
<span class="token number">4</span><span class="token punctuation">)</span> <span class="token string">"tianjin"</span>
<span class="token number">5</span><span class="token punctuation">)</span> <span class="token string">"beijing"</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> zrem china:city tianjin <span class="token comment"># 移除一个元素</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Hyperloglog"><a href="#Hyperloglog" class="headerlink" title="Hyperloglog"></a>Hyperloglog</h3><blockquote>
<p>什么是基数？===》一个数据集内不重复的元素的个数</p>
</blockquote>
<p>统计网站的浏览量，一个id访问多次还是一次</p>
<p>Hyperloglog的优点：占用的内存是固定的，2^64不同的元素的技术只需要12KB的内存。而传统的方式用set保存用户的id来统计，占用的内存大，还有很大的误差</p>
<blockquote>
<p>测试使用</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># pfadd key value1 ...添加元素</span>
<span class="token comment"># pfcount key 获取数量</span>
<span class="token comment"># pfmerge newKey oldKey1 oldKey2 合并到newKey，去除重复</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfadd key a b c d e f g h i j <span class="token comment"># 创建第一组元素</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfcount key <span class="token comment">#统计第一组元素中的基数数量</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">10</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfadd key2 abc bca as se <span class="token comment">#创建第二组</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfcount key2
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfmerge key3 key key2 <span class="token comment">#合并两组到key3中，是并集，没有重复的</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> pfcount key3
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">14</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="BitMaps"><a href="#BitMaps" class="headerlink" title="BitMaps"></a>BitMaps</h3><blockquote>
<p>按位存储  </p>
</blockquote>
<p>统计用户信息：活跃不活跃，登录未登录，打卡未打卡！两个状态的码，都可以用bitmaps</p>
<p>Bitmaps位图，数据结构，只有0，1两个状态。<br>比如存一个员工一年的打卡情况，需要365byte,1字节是8byte,则需要46左右byte就可以。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#用bitmaps记录周一到周日的打卡</span>
<span class="token comment"># setbit key  num1 num2</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">0</span> <span class="token number">1</span> 设置0的值
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">1</span> <span class="token number">0</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">2</span> <span class="token number">0</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">3</span> <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">4</span> <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">5</span> <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> setbit sign <span class="token number">6</span> <span class="token number">1</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>

<span class="token comment"># getbit key num1</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getbit sign <span class="token number">2</span> <span class="token comment">#获取2的值</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> getbit sign <span class="token number">4</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>

<span class="token comment"># bitcount key [start end]统计为1的天数</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> bitcount sign
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">4</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Redis事务"><a href="#Redis事务" class="headerlink" title="Redis事务"></a>Redis事务</h3><p><strong>redis单条命令是保证原子性的，但事务不保证原子性</strong></p>
<p>redis事务：</p>
<ul>
<li>开启事务(multi)</li>
<li>命令入队(…)</li>
<li>执行事务(exec)</li>
</ul>
<p>锁：</p>
<ul>
<li>redis实现乐观锁</li>
</ul>
<blockquote>
<p>正常执行事务</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> multi <span class="token comment">#开启事务</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> k1 v1 <span class="token comment">#命令入队</span>
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> k2 v2
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get k2
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> k3 v3
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">exec</span> <span class="token comment">#执行事务</span>
<span class="token number">1</span><span class="token punctuation">)</span> OK
<span class="token number">2</span><span class="token punctuation">)</span> OK
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"v2"</span>
<span class="token number">4</span><span class="token punctuation">)</span> OK
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>discard 放弃事务 ，中间的都不执行</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> multi <span class="token comment">#开启事务</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> k1 v1
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> k2 v2
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> discard <span class="token comment">#放弃事务</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> get k1
<span class="token punctuation">(</span>nil<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>编译时异常，所有事务都不会执行</p>
</blockquote>
<blockquote>
<p>运行时异常，正常的会执行</p>
</blockquote>
<ul>
<li><p>悲观锁</p>
<ul>
<li>悲观锁，正如其名，具有强烈的独占和排他特性。它指的是对数据被外界（包括本系统当前的其他事务，以及来自外部系统的事务处理）修改持保守态度，因此，在整个数据处理过程中，将数据处于锁定状态</li>
</ul>
</li>
<li><p>乐观锁</p>
<ul>
<li>乐观锁机制采取了更加宽松的加锁机制。悲观锁大多数情况下依靠数据库的锁机制实现，以保证操作最大程度的独占性。但随之而来的就是数据库 性能的大量开销，特别是对长事务而言，这样的开销往往无法承受。相对悲观锁而言，乐观锁更倾向于开发运用</li>
<li>获取version</li>
<li>更新的时候比较version</li>
</ul>
</li>
</ul>
<p><strong>用watch来加锁，本身就相当于乐观锁</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> money <span class="token number">10</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> post <span class="token number">0</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token function">watch</span> money <span class="token comment">#监视，加锁，如果是多线程操作的话，会提示失败</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> multi <span class="token comment">#开启事务</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> decrby money <span class="token number">3</span>
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> incrby post <span class="token number">3</span>
QUEUED
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">exec</span> <span class="token comment">#执行事务</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">7</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">3</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> UNWATCH <span class="token comment">#释放锁，停止监视</span>
OK<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="Jedis"><a href="#Jedis" class="headerlink" title="Jedis"></a>Jedis</h2><blockquote>
<p>Jedis是官方推荐的java连接开发工具，使用java操作redis的中间件，如果要用java操作redis的话，我们一定要对Jedis非常熟悉</p>
</blockquote>
<ul>
<li><p>导入对应的依赖</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--导入Jedis包--></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>redis.clients<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>jedis<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>3.3.0<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>
        <span class="token comment">&lt;!--fastjson--></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>com.alibaba<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>fastjson<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>1.2.60<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>连接测试</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java">    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// new Jedis对象</span>
    <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Jedis</span><span class="token punctuation">(</span><span class="token string">"182.92.159.117"</span><span class="token punctuation">,</span> <span class="token number">6379</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// jedis所有命令都是学过的指令</span>

    <span class="token comment">// 输出pong证明连接成功</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">printf</span><span class="token punctuation">(</span>jedis<span class="token punctuation">.</span><span class="token function">ping</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  <img src="https://s1.ax1x.com/2020/07/05/U9343Q.png" alt="redis连接成功"></p>
</li>
<li><p>常用api：就是我们上边的8个类型的语法指令</p>
</li>
</ul>
<h2 id="SpringBoot-整合"><a href="#SpringBoot-整合" class="headerlink" title="SpringBoot 整合"></a>SpringBoot 整合</h2><blockquote>
<p>在spring2.x之后，原来的Jedis变成了lettuce</p>
</blockquote>
<p>jedis：底层采用的直连，多个线程操作，不安全，如果要避免不安全的需要使用jedis pool连接池</p>
<p>lettuce：底层采用netty，实例可以在多个线程中共享，不存在线程不安全的情况，减少线程数量</p>
<p>redis自动配置类源码：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Bean</span>
<span class="token annotation punctuation">@ConditionalOnMissingBean</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"redisTemplate"</span><span class="token punctuation">)</span> <span class="token comment">// 代表我们可以自己写一个来替换他</span>
<span class="token keyword">public</span> <span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> <span class="token function">redisTemplate</span><span class="token punctuation">(</span><span class="token class-name">RedisConnectionFactory</span> redisConnectionFactory<span class="token punctuation">)</span>
		<span class="token keyword">throws</span> <span class="token class-name">UnknownHostException</span> <span class="token punctuation">&#123;</span>
       <span class="token comment">// redis对象都需要序列化，默认的RedisTemplate没有过多的设置</span>
       <span class="token comment">// 两个泛型都是object，需要强制转换</span>
	<span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> template <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	template<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>redisConnectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> template<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token annotation punctuation">@Bean</span>
<span class="token annotation punctuation">@ConditionalOnMissingBean</span>
   <span class="token comment">// string类型是redis中最常使用的，单独提取出来的</span>
<span class="token keyword">public</span> <span class="token class-name">StringRedisTemplate</span> <span class="token function">stringRedisTemplate</span><span class="token punctuation">(</span><span class="token class-name">RedisConnectionFactory</span> redisConnectionFactory<span class="token punctuation">)</span>
		<span class="token keyword">throws</span> <span class="token class-name">UnknownHostException</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">StringRedisTemplate</span> template <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringRedisTemplate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	template<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>redisConnectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> template<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li><p>修改配置文件</p>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml"><span class="token key atrule">spring</span><span class="token punctuation">:</span>
  <span class="token key atrule">redis</span><span class="token punctuation">:</span>
    <span class="token key atrule">host</span><span class="token punctuation">:</span> 182.92.159.117
    <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">6379</span>
    <span class="token key atrule">database</span><span class="token punctuation">:</span> <span class="token number">0</span>  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>测试连接</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Autowired</span>
<span class="token keyword">private</span> <span class="token class-name">RedisTemplate</span> redisTemplate<span class="token punctuation">;</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">void</span> <span class="token function">contextLoads</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// opsForValue就是操作字符串，其他同理</span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">,</span><span class="token string">"zhangsan"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// redisTemplate 操作不同的数据类型，api和我们的指令是一样的</span>
    <span class="token comment">// opsForValue 操作字符串 类似String</span>
    <span class="token comment">// opsForList 操作List 类似List</span>
    <span class="token comment">// opsForSet</span>
    <span class="token comment">// opsForHash</span>
    <span class="token comment">// opsForZSet</span>
    <span class="token comment">// opsForGeo</span>
    <span class="token comment">// opsForHyperLogLog</span>
    <span class="token comment">// 除了进本的操作，我们常用的方法都可以直接通过redisTemplate操作，比如事务，和基本的CRUD</span>
    <span class="token comment">// 获取redis的连接对象</span>
    <span class="token comment">// RedisConnection connection =</span>
    redisTemplate<span class="token punctuation">.</span><span class="token function">getConnectionFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// connection.flushDb();</span>
    <span class="token comment">// connection.flushAll();</span>

    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>redisTemplate<span class="token punctuation">.</span><span class="token function">opsForValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>新建配置类：原生的RedisTemplate功能太少，不能传入中文</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RedisConfig</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> <span class="token function">redisTemplate</span><span class="token punctuation">(</span><span class="token class-name">RedisConnectionFactory</span> redisConnectionFactory<span class="token punctuation">)</span>
            <span class="token keyword">throws</span> <span class="token class-name">UnknownHostException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> template <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RedisTemplate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        template<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>redisConnectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre><code>      // Json序列化配置
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(om);
      // String 的序列化
      StringRedisSerializer stringRedisSerializer = new
              StringRedisSerializer();
      // key采用String的序列化方式
      template.setKeySerializer(stringRedisSerializer);
      // hash的key也采用String的序列化方式
      template.setHashKeySerializer(stringRedisSerializer);
      // value序列化方式采用jackson
      template.setValueSerializer(jackson2JsonRedisSerializer);
      // hash的value序列化方式采用jackson
      template.setHashValueSerializer(jackson2JsonRedisSerializer);
      template.afterPropertiesSet();

      return template;
  &#125;</code></pre>
<p>  }</p>
  <pre class="line-numbers language-none"><code class="language-none">
- 封装RedisTemplate工具类

参考网上

## 进阶
### Redis.conf详解

&gt;单位
![不区分大小写](https:&#x2F;&#x2F;s1.ax1x.com&#x2F;2020&#x2F;07&#x2F;06&#x2F;UCerrT.png)

&gt;包含
![像spring一样可以导入其他配置文件](https:&#x2F;&#x2F;s1.ax1x.com&#x2F;2020&#x2F;07&#x2F;06&#x2F;UCeWGR.png)

&gt;网络


&#96;&#96;&#96;bash
bind 127.0.0.1 # 绑定的ip
protected-mode yes # 保护模式
port 6379 # 端口设置
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>通用 GENERAL</p>
</blockquote>
</li>
</ul>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">daemonize <span class="token function">yes</span> <span class="token comment"># 以守护进程的方式运行，默认是 no，我们需要自己开启为yes！</span>
pidfile /var/run/redis_6379.pid <span class="token comment"># 如果以后台的方式运行，我们就需要指定一个 pid 文件！</span>
<span class="token comment"># 日志</span>
<span class="token comment"># Specify the server verbosity level.</span>
<span class="token comment"># This can be one of:</span>

<span class="token comment"># debug (a lot of information, useful for development/testing) 开发测试环境</span>
<span class="token comment"># verbose (many rarely useful info, but not a mess like the debug level)</span>
<span class="token comment"># notice (moderately verbose, what you want in production probably) 生产环境</span>
<span class="token comment"># warning (only very important / critical messages are logged)</span>
loglevel notice
logfile <span class="token string">""</span> <span class="token comment"># 日志的文件位置名</span>
databases <span class="token number">16</span> <span class="token comment"># 数据库的数量，默认是 16 个数据库</span>
always-show-logo <span class="token function">yes</span> <span class="token comment"># 是否总是显示LOGO</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>快照  </p>
</blockquote>
<p>持久化， 在规定的时间内，执行了多少次操作，则会持久化到文件 .rdb. aof<br>redis 是内存数据库，如果没有持久化，那么数据断电及失！</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 如果900s内，如果至少有一个1 key进行了修改，我们及进行持久化操作</span>
save <span class="token number">900</span> <span class="token number">1</span>
<span class="token comment"># 如果300s内，如果至少10 key进行了修改，我们及进行持久化操作</span>
save <span class="token number">300</span> <span class="token number">10</span>
<span class="token comment"># 如果60s内，如果至少10000 key进行了修改，我们及进行持久化操作</span>
save <span class="token number">60</span> <span class="token number">10000</span>
<span class="token comment"># 我们之后学习持久化，会自己定义这个测试！</span>
stop-writes-on-bgsave-error <span class="token function">yes</span> <span class="token comment"># 持久化如果出错，是否还需要继续工作！</span>
rdbcompression <span class="token function">yes</span> <span class="token comment"># 是否压缩 rdb 文件，需要消耗一些cpu资源！</span>
rdbchecksum <span class="token function">yes</span> <span class="token comment"># 保存rdb文件的时候，进行错误的检查校验！</span>
<span class="token function">dir</span> ./ <span class="token comment"># rdb 文件保存的目录！</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>REPLICATION 复制，我们后面讲解主从复制的，时候再进行讲解</p>
</blockquote>
<blockquote>
<p>SECURITY</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token function">ping</span>
PONG
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> config get requirepass <span class="token comment"># 获取redis的密码</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"requirepass"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">""</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> config <span class="token builtin class-name">set</span> requirepass <span class="token string">"123456"</span> <span class="token comment"># 设置redis的密码</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> config get requirepass <span class="token comment"># 发现所有的命令都没有权限了</span>
<span class="token punctuation">(</span>error<span class="token punctuation">)</span> NOAUTH Authentication required.
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token function">ping</span>
<span class="token punctuation">(</span>error<span class="token punctuation">)</span> NOAUTH Authentication required.
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> auth <span class="token number">123456</span> <span class="token comment"># 使用密码进行登录！</span>
OK
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> config get requirepass
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"requirepass"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"123456"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>修改完要记得重启redis</strong></p>
<blockquote>
<p>限制 CLIENTS</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">maxclients <span class="token number">10000</span> <span class="token comment"># 设置能连接上redis的最大客户端的数量</span>
maxmemory <span class="token operator">&lt;</span>bytes<span class="token operator">></span> <span class="token comment"># redis 配置最大的内存容量</span>
maxmemory-policy noeviction <span class="token comment"># 内存到达上限之后的处理策略</span>
<span class="token number">1</span>、volatile-lru：只对设置了过期时间的key进行LRU（默认值）
<span class="token number">2</span>、allkeys-lru ： 删除lru算法的key
<span class="token number">3</span>、volatile-random：随机删除即将过期key
<span class="token number">4</span>、allkeys-random：随机删除
<span class="token number">5</span>、volatile-ttl ： 删除即将过期的
<span class="token number">6</span>、noeviction ： 永不过期，返回错误<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>APPEND ONLY 模式 aof配置</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">appendonly no <span class="token comment"># 默认是不开启aof模式的，默认是使用rdb方式持久化的，在大部分所有的情况下，</span>
rdb完全够用！
appendfilename <span class="token string">"appendonly.aof"</span> <span class="token comment"># 持久化的文件的名字</span>
<span class="token comment"># appendfsync always # 每次修改都会 sync。消耗性能</span>
appendfsync everysec <span class="token comment"># 每秒执行一次 sync，可能会丢失这1s的数据！</span>
<span class="token comment"># appendfsync no # 不执行 sync，这个时候操作系统自己同步数据，速度最快！</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Redis持久化"><a href="#Redis持久化" class="headerlink" title="Redis持久化"></a>Redis持久化</h3><blockquote>
<p>Redis 是内存数据库，如果不将内存中的数据库状态保存到磁盘，那么一旦服务器进程退出，服务器中的数据库状态也会消失。所以 Redis 提供了持久化功能！</p>
</blockquote>
<h4 id="RDB-Redis-DataBase"><a href="#RDB-Redis-DataBase" class="headerlink" title="RDB(Redis DataBase)"></a>RDB(Redis DataBase)</h4><blockquote>
<p>在主从复制中，rdb就是备用了！从机上面！</p>
</blockquote>
<p>Redis会单独创建（fork）一个子进程来进行持久化，会先将数据写入到一个临时文件中，待持久化过程<br>都结束了，再用这个临时文件替换上次持久化好的文件。整个过程中，主进程是不进行任何IO操作的。<br>这就确保了极高的性能。如果需要进行大规模数据的恢复，且对于数据恢复的完整性不是非常敏感，那<br>RDB方式要比AOF方式更加的高效。RDB的缺点是最后一次持久化后的数据可能丢失。我们默认的就是<br>RDB，一般情况下不需要修改这个配置！</p>
<p><strong>rdb保存的文件是dump.rdb</strong> 都是在我们的配置文件中快照中进行配置的！</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UC1oUf.png" alt="test"></p>
<blockquote>
<p>触发机制</p>
</blockquote>
<ol>
<li>save的规则满足的情况下，会自动触发rdb规则</li>
<li>执行 flushall 命令，也会触发我们的rdb规则！</li>
<li>退出redis，也会产生 rdb 文件！  </li>
</ol>
<p><strong>备份就自动生成一个 dump.rdb</strong></p>
<blockquote>
<p>恢复rdb文件</p>
</blockquote>
<ol>
<li>只需要将rdb文件放在我们redis启动目录就可以，redis启动的时候会自动检查dump.rdb 恢复其中的数据</li>
<li>查看需要存在的位置<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> config get <span class="token function">dir</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"dir"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"/usr/local/bin"</span> <span class="token comment"># 如果在这个目录下存在dump.rdb 文件，启动就会自动恢复其中的数据</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></li>
<li>优点：<ol>
<li>适合大规模的数据恢复</li>
<li>对数据的完整性要不高</li>
</ol>
</li>
<li>缺点：<ol>
<li>需要一定的时间间隔进程操作！如果redis意外宕机了，这个最后一次修改数据就没有的了！</li>
<li>fork进程的时候，会占用一定的内容空间</li>
</ol>
</li>
</ol>
<h4 id="AOF（Append-Only-File）"><a href="#AOF（Append-Only-File）" class="headerlink" title="AOF（Append Only File）"></a>AOF（Append Only File）</h4><blockquote>
<p>将我们的所有命令都记录下来，类似于history，恢复的时候就把这个文件全部在执行一遍！</p>
</blockquote>
<p>以日志的形式来记录每个写操作，将Redis执行过的所有指令记录下来（读操作不记录），只许追加文件但不可以改写文件，redis启动之初会读取该文件重新构建数据，换言之，redis重启的话就根据日志文件的内容将写指令从前到后执行一次以完成数据的恢复工作</p>
<p><strong>Aof保存的是 appendonly.aof 文件</strong></p>
<p>默认是不开启的，我们需要手动进行配置！我们只需要将 appendonly 改为yes就开启了 aof，然后重启，redis 就可以生效了<br><img src="https://s1.ax1x.com/2020/07/06/UCURBQ.png" alt="开启aof"></p>
<p>如果aof文件有问题，redis就会报错，我们可以用自带的修复工具 redis-check-aof –fix</p>
<p><code>redis-check-aof --fix appendonly.aof</code>即可修复</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UCUvNR.png" alt="check"></p>
<blockquote>
<p>重写规则说明</p>
</blockquote>
<p>如果aof文件大于64m，就会开辟一个新的进程把我们的文件进行重写<br><img src="https://s1.ax1x.com/2020/07/06/UCacP1.png" alt="重写规则"></p>
<blockquote>
<p>优缺点</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">appendonly no <span class="token comment"># 默认是不开启aof模式的，默认是使用rdb方式持久化的，在大部分所有的情况下，</span>
rdb完全够用！
appendfilename <span class="token string">"appendonly.aof"</span> <span class="token comment"># 持久化的文件的名字</span>
<span class="token comment"># appendfsync always # 每次修改都会 sync。消耗性能</span>
appendfsync everysec <span class="token comment"># 每秒执行一次 sync，可能会丢失这1s的数据！</span>
<span class="token comment"># appendfsync no # 不执行 sync，这个时候操作系统自己同步数据，速度最快！</span>
<span class="token comment"># rewrite 重写，</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>优点：<ul>
<li>每一次修改都同步，文件的完整会更加好</li>
<li>每秒同步一次，可能会丢失一秒的数据</li>
<li>从不同步，效率最高的</li>
</ul>
</li>
<li>缺点：<ul>
<li>相对于数据文件来说，aof远远大于 rdb，修复的速度也比 rdb慢</li>
<li>Aof 运行效率也要比 rdb 慢，所以我们redis默认的配置就是rdb持久化</li>
</ul>
</li>
</ul>
<p>扩展：</p>
<ol>
<li>RDB 持久化方式能够在指定的时间间隔内对你的数据进行快照存储</li>
<li>AOF 持久化方式记录每次对服务器写的操作，当服务器重启的时候会重新执行这些命令来恢复原始的数据，AOF命令以Redis 协议追加保存每次写的操作到文件末尾，Redis还能对AOF文件进行后台重写，使得AOF文件的体积不至于过大。</li>
<li><strong>只做缓存，如果你只希望你的数据在服务器运行的时候存在，你也可以不使用任何持久化</strong></li>
<li>同时开启两种持久化方式<ol>
<li>在这种情况下，当redis重启的时候会优先载入AOF文件来恢复原始的数据，因为在通常情况下AOF<br>文件保存的数据集要比RDB文件保存的数据集要完整。</li>
<li>RDB 的数据不实时，同时使用两者时服务器重启也只会找AOF文件，那要不要只使用AOF呢？作者建议不要，因为RDB更适合用于备份数据库（AOF在不断变化不好备份），快速重启，而且不会有AOF可能潜在的Bug，留着作为一个万一的手段。</li>
</ol>
</li>
<li>性能建议<ol>
<li>因为RDB文件只用作后备用途，建议只在Slave上持久化RDB文件，而且只要15分钟备份一次就够了，只保留 save 900 1 这条规则。</li>
<li>如果Enable AOF ，好处是在最恶劣情况下也只会丢失不超过两秒数据，启动脚本较简单只load自己的AOF文件就可以了，代价一是带来了持续的IO，二是AOF rewrite 的最后将 rewrite 过程中产生的新数据写到新文件造成的阻塞几乎是不可避免的。只要硬盘许可，应该尽量减少AOF rewrite的频率，AOF重写的基础大小默认值64M太小了，可以设到5G以上，默认超过原大小100%大小重写可以改到适当的数值。</li>
<li>如果不Enable AOF ，仅靠 Master-Slave Repllcation 实现高可用性也可以，能省掉一大笔IO，也减少了rewrite时带来的系统波动。代价是如果Master/Slave 同时倒掉，会丢失十几分钟的数据，启动脚本也要比较两个 Master/Slave 中的 RDB文件，载入较新的那个，微博就是这种架构。</li>
</ol>
</li>
</ol>
<h3 id="Redis-发布订阅"><a href="#Redis-发布订阅" class="headerlink" title="Redis 发布订阅"></a>Redis 发布订阅</h3><blockquote>
<p>Redis 发布订阅(pub/sub)是一种消息通信模式：发送者(pub)发送消息，订阅者(sub)接收消息。微信、微博、关注系统！</p>
</blockquote>
<p>Redis 客户端可以订阅任意数量的频道</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UP8xJK.png" alt="流程图"></p>
<blockquote>
<p>这些命令被广泛用于构建即时通信应用，比如网络聊天室(chatroom)和实时广播、实时提醒等。</p>
</blockquote>
<table>
<thead>
<tr>
<th align="center">序号</th>
<th align="center">命令及描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center"><code>Psubscribe pattern [parrten2 ....]</code><br>订阅一个或多个符合给定模式的频道</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center"><code>Pubsub &lt;subcommand&gt; [argument [argument ...]]</code><br>查看订阅与发布系统状态</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center"><code>Publish channel message</code><br>将信息发送到指定的频道</td>
</tr>
<tr>
<td align="center">4</td>
<td align="center"><code>Punsubscribe [pattern [pattern ...]]</code><br>退订所有给定模式的频道</td>
</tr>
<tr>
<td align="center">5</td>
<td align="center"><code>Subscribe channel [channel ...]</code><br>订阅给定的一个或多个频道的信息</td>
</tr>
<tr>
<td align="center">6</td>
<td align="center"><code>Unsubscribe [channel [channel ...]]</code><br>指退订给定的频道</td>
</tr>
</tbody></table>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> subscribe zhy <span class="token comment"># 订阅一个频道</span>
Reading messages<span class="token punctuation">..</span>. <span class="token punctuation">(</span>press Ctrl-C to quit<span class="token punctuation">)</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"subscribe"</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"zhy"</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token comment"># 等待读取推送的信息</span>
<span class="token number">1</span><span class="token punctuation">)</span> <span class="token string">"message"</span> <span class="token comment"># 消息</span>
<span class="token number">2</span><span class="token punctuation">)</span> <span class="token string">"zhy"</span> <span class="token comment"># 推送频道</span>
<span class="token number">3</span><span class="token punctuation">)</span> <span class="token string">"nihao"</span> <span class="token comment"># 具体内容</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> publish zhy nihao <span class="token comment"># 发布者发布消息到频道</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span> <span class="token comment"># 这个地方显示的是发送给了多少人</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> PUBLISH zhy <span class="token builtin class-name">test</span> <span class="token comment"># 一旦退订或者退出，这个消息就接收不到了</span>
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>使用场景：</p>
</blockquote>
<ol>
<li>实时消息系统！</li>
<li>事实聊天！（频道当做聊天室，将信息回显给所有人即可！）</li>
<li>订阅，关注系统都是可以的！<br>稍微复杂的场景我们就会使用消息中间件</li>
</ol>
<h3 id="Redis主从复制"><a href="#Redis主从复制" class="headerlink" title="Redis主从复制"></a>Redis主从复制</h3><h4 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h4><p>主从复制，是指将一台Redis服务器的数据，复制到其他的Redis服务器。前者称为主节点(master/leader)，后者称为从节点(slave/follower)；数据的复制是单向的，只能由主节点到从节点。Master以写为主，Slave 以读为主。</p>
<p>主从复制的作用主要包括：</p>
<ol>
<li>数据冗余：主从复制实现了数据的热备份，是持久化之外的一种数据冗余方式。</li>
<li>故障恢复：当主节点出现问题时，可以由从节点提供服务，实现快速的故障恢复；实际上是一种服务的冗余。</li>
<li>负载均衡：在主从复制的基础上，配合读写分离，可以由主节点提供写服务，由从节点提供读服务（即写Redis数据时应用连接主节点，读Redis数据时应用连接从节点），分担服务器负载；尤其是在写少读多的场景下，通过多个从节点分担读负载，可以大大提高Redis服务器的并发量。</li>
<li>高可用（集群）基石：除了上述作用以外，主从复制还是哨兵和集群能够实施的基础，因此说主从复制是Redis高可用的基础。</li>
</ol>
<p><img src="https://s1.ax1x.com/2020/07/06/UPBnN4.png" alt="一主三从"></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># info replication 显示当前redis的主从信息</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> info replication
<span class="token comment"># Replication</span>
role:master
connected_slaves:0
master_replid:d49ac9bced0770f85ae058fd82de58d218ada58e
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>配置需要修改的地方：</p>
<ol>
<li>端口</li>
<li>pid名字</li>
<li>log名字</li>
<li>dump.rdb名字</li>
</ol>
<p>修改完毕之后启动<br><img src="https://s1.ax1x.com/2020/07/06/UPyYQA.png" alt="看后台进程"></p>
<h4 id="一主二从"><a href="#一主二从" class="headerlink" title="一主二从"></a>一主二从</h4><p><strong>默认情况下，每台Redis服务器都是主节点</strong>； 我们一般情况下只用配置从机就好了！</p>
<p>语法:<code>slaveof host port</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:638<span class="token operator"><span class="token file-descriptor important">0</span>></span> SLAVEOF <span class="token number">127.0</span>.0.1 <span class="token number">6379</span> <span class="token comment"># SLAVEOF host 6379 绑定主机</span>
OK
<span class="token number">127.0</span>.0.1:638<span class="token operator"><span class="token file-descriptor important">0</span>></span> info replication <span class="token comment"># 查看信息</span>
<span class="token comment"># Replication</span>
role:slave <span class="token comment"># 当前角色是从机</span>
master_host:127.0.0.1 <span class="token comment"># 可以的看到主机的信息</span>
master_port:6379

<span class="token comment">###主机的视角</span>
<span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> info replication
<span class="token comment"># Replication</span>
role:master
connected_slaves:1 <span class="token comment"># 多了从机的配置</span>
slave0:ip<span class="token operator">=</span><span class="token number">127.0</span>.0.1,port<span class="token operator">=</span><span class="token number">6380</span>,state<span class="token operator">=</span>online,offset<span class="token operator">=</span><span class="token number">42</span>,lag<span class="token operator">=</span><span class="token number">1</span> <span class="token comment"># 多了从机的配置</span>
master_replid:a81be8dd257636b2d3e7a9f595e69d73ff03774e
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:42
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:42<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://s1.ax1x.com/2020/07/06/UPcvxH.png" alt="主机信息"></p>
<p><strong>注意：</strong>命令配置是暂时的，要想永久性配置需要去修改配置文件！</p>
<blockquote>
<p><strong>主机设置值</strong></p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> <span class="token builtin class-name">set</span> user zhangsan
OK<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p><strong>从机会自动同步主机写入的值</strong></p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:638<span class="token operator"><span class="token file-descriptor important">0</span>></span> get user
<span class="token string">"zhangsan"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p><strong>但是从机不可以写入</strong></p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:638<span class="token operator"><span class="token file-descriptor important">1</span>></span> <span class="token builtin class-name">set</span> k2 <span class="token number">2</span>
<span class="token punctuation">(</span>error<span class="token punctuation">)</span> READONLY You can't <span class="token function">write</span> against a <span class="token builtin class-name">read</span> only replica.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p><strong>主机宕机后，从机依旧连接到主机执行读操作，但是没有写操作，如果主机恢复，，从机依旧可以直接获取到主机写的信息</strong></p>
</blockquote>
<blockquote>
<p><strong>如果是使用命令行，来配置的主从，这个时候如果重启了，就会变回主机！只要变为从机，立马就会从主机中获取值</strong></p>
</blockquote>
<blockquote>
<p>复制原理</p>
</blockquote>
<ul>
<li>Slave 启动成功连接到 master 后会发送一个sync同步命令</li>
<li>Master 接到命令，启动后台的存盘进程，同时收集所有接收到的用于修改数据集命令，在后台进程执行完毕之后，master将传送整个数据文件到slave，并完成一次完全同步。</li>
<li>全量复制：slave服务在接收到数据库文件数据后，将其存盘并加载到内存中。</li>
<li>增量复制：Master继续将新的所有收集到的修改命令依次传给slave，完成同步</li>
</ul>
<h3 id="哨兵模式"><a href="#哨兵模式" class="headerlink" title="哨兵模式"></a>哨兵模式</h3><blockquote>
<p>概述<br>主从切换技术的方法是：当主服务器宕机后，需要手动把一台从服务器切换为主服务器，这就需要人工干预，费事费力，还会造成一段时间内服务不可用。这不是一种推荐的方式，更多时候，我们优先考虑哨兵模式。Redis从2.8开始正式提供了Sentinel（哨兵） 架构来解决这个问题。</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/07/06/UPbCct.png" alt="UPbCct.png"></p>
<p>假设主服务器宕机，哨兵1先检测到这个结果，系统并不会马上进行failover过程，仅仅是哨兵1主观的认<br>为主服务器不可用，这个现象成为<strong>主观下线</strong>。当后面的哨兵也检测到主服务器不可用，并且数量达到一<br>定值时，那么哨兵之间就会进行一次投票，投票的结果由一个哨兵发起，进行failover <strong>故障转移</strong> 操作。<br>切换成功后，就会通过发布订阅模式，让各个哨兵把自己监控的从服务器实现切换主机，这个过程称为客观下线。</p>
<ul>
<li>优点：<ul>
<li>哨兵集群，基于主从复制模式，所有的主从配置优点，它全有</li>
<li>主从可以切换，故障可以转移，系统的可用性就会更好</li>
<li>哨兵模式就是主从模式的升级，手动到自动，更加健壮</li>
</ul>
</li>
<li>缺点：<ul>
<li>Redis不好在线扩容，集群容量一旦到达上限，在线扩容就十分麻烦</li>
<li>实现哨兵模式的配置其实是很麻烦，里面有很多选择</li>
</ul>
</li>
</ul>
<blockquote>
<p>哨兵模式的全部配置</p>
</blockquote>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># Example sentinel.conf</span>
<span class="token comment"># 哨兵sentinel实例运行的端口 默认26379</span>
port <span class="token number">26379</span>
<span class="token comment"># 哨兵sentinel的工作目录</span>
<span class="token function">dir</span> /tmp
<span class="token comment"># 哨兵sentinel监控的redis主节点的 ip port</span>
<span class="token comment"># master-name 可以自己命名的主节点名字 只能由字母A-z、数字0-9 、这三个字符".-_"组成。</span>
<span class="token comment"># quorum 配置多少个sentinel哨兵统一认为master主节点失联 那么这时客观上认为主节点失联了</span>
<span class="token comment"># sentinel monitor &lt;master-name> &lt;ip> &lt;redis-port> &lt;quorum></span>
sentinel monitor mymaster <span class="token number">127.0</span>.0.1 <span class="token number">6379</span> <span class="token number">2</span>
<span class="token comment"># 当在Redis实例中开启了requirepass foobared 授权密码 这样所有连接Redis实例的客户端都要提供密码</span>
<span class="token comment"># 设置哨兵sentinel 连接主从的密码 注意必须为主从设置一样的验证密码</span>
<span class="token comment"># sentinel auth-pass &lt;master-name> &lt;password></span>
sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
<span class="token comment"># 指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒</span>
<span class="token comment"># sentinel down-after-milliseconds &lt;master-name> &lt;milliseconds></span>
sentinel down-after-milliseconds mymaster <span class="token number">30000</span>
<span class="token comment"># 这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行 同步，这个数字越小，完成failover所需的时间就越长，但是如果这个数字越大，就意味着越 多的slave因为replication而不可用。可以通过将这个值设为 1 来保证每次只有一个slave 处于不能处理命令请求的状态。</span>
<span class="token comment"># sentinel parallel-syncs &lt;master-name> &lt;numslaves></span>
sentinel parallel-syncs mymaster <span class="token number">1</span>
<span class="token comment"># 故障转移的超时时间 failover-timeout 可以用在以下这些方面：</span>
<span class="token comment">#1. 同一个sentinel对同一个master两次failover之间的间隔时间。</span>
<span class="token comment">#2. 当一个slave从一个错误的master那里同步数据开始计算时间。直到slave被纠正为向正确的master那里同步数据时。</span>
<span class="token comment">#3.当想要取消一个正在进行的failover所需要的时间。</span>
<span class="token comment">#4.当进行failover时，配置所有slaves指向新的master所需的最大时间。不过，即使过了这个超时，slaves依然会被正确配置为指向master，但是就不按parallel-syncs所配置的规则来了</span>
<span class="token comment"># 默认三分钟</span>
<span class="token comment"># sentinel failover-timeout &lt;master-name> &lt;milliseconds></span>

sentinel failover-timeout mymaster <span class="token number">180000</span>
<span class="token comment"># SCRIPTS EXECUTION</span>
<span class="token comment">#配置当某一事件发生时所需要执行的脚本，可以通过脚本来通知管理员，例如当系统运行不正常时发邮件通知相关人员。</span>
<span class="token comment">#对于脚本的运行结果有以下规则：</span>
<span class="token comment">#若脚本执行后返回1，那么该脚本稍后将会被再次执行，重复次数目前默认为10</span>
<span class="token comment">#若脚本执行后返回2，或者比2更高的一个返回值，脚本将不会重复执行。</span>
<span class="token comment">#如果脚本在执行过程中由于收到系统中断信号被终止了，则同返回值为1时的行为相同。</span>
<span class="token comment">#一个脚本的最大执行时间为60s，如果超过这个时间，脚本将会被一个SIGKILL信号终止，之后重新执行。</span>
<span class="token comment">#通知型脚本:当sentinel有任何警告级别的事件发生时（比如说redis实例的主观失效和客观失效等等），将会去调用这个脚本，这时这个脚本应该通过邮件，SMS等方式去通知系统管理员关于系统不正常运行的信息。调用该脚本时，将传给脚本两个参数，一个是事件的类型，一个是事件的描述。如果sentinel.conf配置文件中配置了这个脚本路径，那么必须保证这个脚本存在于这个路径，并且是可执行的，否则sentinel无法正常启动成功。</span>
<span class="token comment">#通知脚本</span>
<span class="token comment"># shell编程</span>
<span class="token comment"># sentinel notification-script &lt;master-name> &lt;script-path></span>
sentinel notification-script mymaster /var/redis/notify.sh
<span class="token comment"># 客户端重新配置主节点参数脚本</span>
<span class="token comment"># 当一个master由于failover而发生改变时，这个脚本将会被调用，通知相关的客户端关于master地址已经发生改变的信息。</span>
<span class="token comment"># 以下参数将会在调用脚本时传给脚本:</span>
<span class="token comment"># &lt;master-name> &lt;role> &lt;state> &lt;from-ip> &lt;from-port> &lt;to-ip> &lt;to-port></span>
<span class="token comment"># 目前&lt;state>总是“failover”,</span>
<span class="token comment"># &lt;role>是“leader”或者“observer”中的一个。</span>
<span class="token comment"># 参数 from-ip, from-port, to-ip, to-port是用来和旧的master和新的master(即旧的slave)通信的</span>
<span class="token comment"># 这个脚本应该是通用的，能被多次调用，不是针对性的。</span>
<span class="token comment"># sentinel client-reconfig-script &lt;master-name> &lt;script-path>sentinel client-reconfig-script mymaster /var/redis/reconfig.sh # 一般都是由运维来配置！</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="Redis缓存穿透和雪崩"><a href="#Redis缓存穿透和雪崩" class="headerlink" title="Redis缓存穿透和雪崩"></a>Redis缓存穿透和雪崩</h3><h4 id="缓存穿透（查不到）"><a href="#缓存穿透（查不到）" class="headerlink" title="缓存穿透（查不到）"></a>缓存穿透（查不到）</h4><blockquote>
<p>概念</p>
</blockquote>
<p>用户想要查询一个数据，发现redis内存数据库没有，也就是缓存没有命中，于是向持久层数据库查询。发现也没有，于是本次查询失败。当用户很多的时候，缓存都没有命中（秒杀！），于是都去请求了持久层数据库。这会给持久层数据库造成很大的压力，这时候就相当于出现了缓存穿透。<br><img src="https://s1.ax1x.com/2020/07/06/UiMpjA.png" alt="正常执行过程"></p>
<blockquote>
<p>解决方案</p>
</blockquote>
<p><strong>布隆过滤器</strong><br>布隆过滤器是一种数据结构，对所有可能查询的参数以hash形式存储，在控制层先进行校验，不符合则丢弃，从而避免了对底层存储系统的查询压力；</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UiMJCF.png" alt="布隆过滤器"></p>
<p><strong>缓存空对象</strong>  </p>
<p>当存储层不命中后，即使返回的空对象也将其缓存起来，同时会设置一个过期时间，之后再访问这个数据将会从缓存中获取，保护了后端数据源；<br><img src="https://s1.ax1x.com/2020/07/06/UiMBE6.png" alt="缓存空对象"></p>
<p>但是这种方法会存在两个问题：</p>
<ol>
<li>如果空值能够被缓存起来，这就意味着缓存需要更多的空间存储更多的键，因为这当中可能会有很多的空值的键；</li>
<li>即使对空值设置了过期时间，还是会存在缓存层和存储层的数据会有一段时间窗口的不一致，这对于需要保持一致性的业务会有影响（当你的数据库内有了值，但是缓存里依旧是null）</li>
</ol>
<h4 id="缓存击穿（量太大，缓存过期！）"><a href="#缓存击穿（量太大，缓存过期！）" class="headerlink" title="缓存击穿（量太大，缓存过期！）"></a>缓存击穿（量太大，缓存过期！）</h4><blockquote>
<p>概述</p>
</blockquote>
<p>当某个key在过期的瞬间，有大量的请求并发访问，这类数据一般是热点数据，由于缓存过期，会同时访问数据库来查询最新数据，并且回写缓存，会导使数据库瞬间压力过大。</p>
<blockquote>
<p>解决方案</p>
</blockquote>
<p><strong>设置热点数据永不过期</strong><br>从缓存层面来看，没有设置过期时间，所以不会出现热点 key 过期后产生的问题</p>
<p><strong>加互斥锁</strong><br>分布式锁：使用分布式锁，保证对于每个key同时只有一个线程去查询后端服务，其他线程没有获得分布式锁的权限，因此只需要等待即可。这种方式将高并发的压力转移到了分布式锁，因此对分布式锁的考验很大</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UiQFM9.png" alt="加一个锁来控制"></p>
<h4 id="缓存雪崩"><a href="#缓存雪崩" class="headerlink" title="缓存雪崩"></a>缓存雪崩</h4><blockquote>
<p>概念</p>
</blockquote>
<p>缓存雪崩，是指在某一个时间段，缓存集中过期失效，然后Redis宕机</p>
<p><img src="https://s1.ax1x.com/2020/07/06/UiQYIf.png" alt="缓存雪崩"></p>
<p>比如马上就要到双11零点，很快就会迎来一波抢购，这波商品时间比较集中的放入了缓存，假设缓存一个小时。那么到了凌晨一点钟的时候，这批商品的缓存就都过期了。而对这批商品的访问查询，都落到了数据库上，对于数据库而言，就会产生周期性的压力波峰。于是所有的请求都会达到存储层，存储层的调用量会暴增，造成存储层也会挂掉的情况。</p>
<blockquote>
<p>解决方案</p>
</blockquote>
<p><strong>redis高可用</strong><br>这个思想的含义是，既然redis有可能挂掉，那我多增设几台redis，这样一台挂掉之后其他的还可以继续工作，其实就是搭建的集群。（异地多活！）</p>
<p><strong>限流降级</strong><br>这个解决方案的思想是，在缓存失效后，通过加锁或者队列来控制读数据库写缓存的线程数量。比如对某个key只允许一个线程查询数据和写缓存，其他线程等待。</p>
<p><strong>数据预热</strong><br>数据加热的含义就是在正式部署之前，我先把可能的数据先预先访问一遍，这样部分可能大量访问的数据就会加载到缓存中。在即将发生大并发访问前手动触发加载缓存不同的key，设置不同的过期时间，让缓存失效的时间点尽量均匀。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Max</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhy2021.github.io/2020/07/04/redis-xue-xi/">https://zhy2021.github.io/2020/07/04/redis-xue-xi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Max</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/redis/">
                                    <span class="chip bg-color">redis</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: '5FkhQebEqGdoNnuL654mv5KM-gzGzoHsz',
        appKey: 'NNEBzCiygD4tBLqHt8diLxda',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/07/27/zookeeper-xue-xi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="Zookeeper学习">
                        
                        <span class="card-title">Zookeeper学习</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            ZooKeeper是一个分布式的，开放源码的分布式应用程序协调服务
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-07-27
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Zookeeper/" class="post-category">
                                    Zookeeper
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E6%8A%80%E6%9C%AF/">
                        <span class="chip bg-color">分布式技术</span>
                    </a>
                    
                    <a href="/tags/Zookeeper/">
                        <span class="chip bg-color">Zookeeper</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/06/28/swagger/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/4.jpg" class="responsive-img" alt="swagger学习">
                        
                        <span class="card-title">swagger学习</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            接口文档实时动态生成,大大简化了后端的工作，不会出现接口文档与实际情况不一致的情况
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-06-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/swagger/" class="post-category">
                                    swagger
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/swagger/">
                        <span class="chip bg-color">swagger</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Max|Blog<br />'
            + '文章作者: Max<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default"></script>

    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="2844914148"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Max</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">141.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "2";
                    var startDate = "13";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1181062873@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1181062873" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1181062873" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
